#include "game.h"

#include <iostream>

#include <cstdlib>
#include <cstring>

#include "misc.h"

#include <string>

#include "log.h"

using namespace std;

char* Game::parse_proto(char* p, int len,char* data) {
	int tmp;
	if (p[0] == 'C') {  // SERVER side code
		p++;
		*lg << "parse_proto: C" <<fl;
		if (p[0] == 'N') {
			*lg<< "parse_proto: N" <<fl;
			p++;
			tmp = find_delim(p, strlen(p));
			if (strncmp(p, "Player", tmp) == 0) {
				Player *pl = new Player();
				pl->parse_proto(p+tmp+1, strlen(p+tmp+1));
				players[players.size()+1] = pl;
				char *msg=new char[1000];
				sprintf(msg,"!SN%s,%d,Player,N%d,%s",
					data,
					players.size(),
					strlen(pl->get_nick().c_str()), pl->get_nick().c_str()
					);
				*lg<<"parse_proto: ret msg:"<<msg<<fl;
				return msg;
			};
		};



	}	else if (p[0] == 'S') { // CLIENT side
		p++;
		if (p[0] == 'N') {
			p++;
			int i;
			//tmp = find_delim(p, strlen(p));
			i = atoi(p);
			//p+= tmp;
			if (strncmp(p, data, i)==0) { 
        *lg << "Our ID!" << fl;
      } else {
        *lg << "Other ID" << fl;
        *lg << p << ' ' << data << ' ' << i << fl;
      };
			p+= i+1;
			i = atoi(p);
      *lg << "Player id: " << i << fl;
      p+= i+1;
			tmp = find_delim(p, strlen(p));
			if (strncmp(p, "Player", tmp) == 0) {
				Player *pl = new Player();
				pl->parse_proto(p+tmp+1, strlen(p+tmp+1));
				players[i] = pl;
				
        *lg << "New Player: " << pl->get_nick().c_str() << fl;

/*				char *msg=new char[1000];
				sprintf(msg,"!SN%d,%s,%d,Player,N%d,%s",
					36, data,
					players.size(),
					strlen(pl->get_nick().c_str()), pl->get_nick().c_str()
					);
				return msg;*/
			};
		};
	};
	return 0;
};

Game::Game() {
	*lg << "Game::Game()" << fl;
};

